package com.codingapi.p2p.client.service.impl;

import com.codingapi.p2p.client.handler.NettyServerHandler;
import com.codingapi.p2p.client.service.NettyServerService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.InetSocketAddress;

/**
 * create by lorne on 2018/3/13
 */

public class NettyServerServiceImpl implements NettyServerService {


    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    private String host;
    private int port;

    public NettyServerServiceImpl(String host,int port) {
        this.host = host;
        this.port = port;
    }

    private Logger logger = LoggerFactory.getLogger(NettyServerServiceImpl.class);

    @Override
    public void start() {
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_REUSEADDR,true)
//                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) {
                            ChannelPipeline p = ch.pipeline();

                            p.addLast(new NettyServerHandler());
                        }
                    });
            b.bind(new InetSocketAddress(InetAddress.getLocalHost().getHostAddress(),port));



            logger.info("netty server- listener ! ");

        }catch (Exception e){
            close();
        }
    }

    @Override
    public void close() {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();

        logger.info("netty server- close ! ");
    }
}
